package l1j.william;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.DatabaseFactory;
import l1j.server.server.utils.SQLUtil;
import l1j.william.L1WilliamTeleportScroll;

public class TeleportScroll {
	private static Logger _log = Logger.getLogger(TeleportScroll.class
			.getName());

	private static TeleportScroll _instance;

	public static TeleportScroll getInstance() {
		if (_instance == null) {
			_instance = new TeleportScroll();
		}
		return _instance;
	}

	private final HashMap<Integer, L1WilliamTeleportScroll> _itemIdIndex = new HashMap<Integer, L1WilliamTeleportScroll>();

	private TeleportScroll() {
		this.loadTeleportScroll();
	}

	private void fillTeleportScroll(final ResultSet rs) throws SQLException {
		while (rs.next()) {
			final int itemId = rs.getInt("item_id");
			final int tpLocX = rs.getInt("tpLocX");
			final int tpLocY = rs.getInt("tpLocY");
			final short tpMapId = rs.getShort("tpMapId");
			final int check_minLocX = rs.getInt("check_minLocX");
			final int check_minLocY = rs.getInt("check_minLocY");
			final int check_maxLocX = rs.getInt("check_maxLocX");
			final int check_maxLocY = rs.getInt("check_maxLocY");
			final short check_MapId = rs.getShort("check_MapId");
			final int removeItem = rs.getInt("removeItem");

			final L1WilliamTeleportScroll teleport_scroll = new L1WilliamTeleportScroll(
					itemId, tpLocX, tpLocY, tpMapId, check_minLocX,
					check_minLocY, check_maxLocX, check_maxLocY, check_MapId,
					removeItem);
			this._itemIdIndex.put(itemId, teleport_scroll);
		}
	}

	public L1WilliamTeleportScroll getTemplate(final int itemId) {
		return this._itemIdIndex.get(itemId);
	}

	private void loadTeleportScroll() {
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {

			con = DatabaseFactory.get().getConnection();
			pstm = con
					.prepareStatement("SELECT * FROM william_teleport_scroll");
			rs = pstm.executeQuery();
			this.fillTeleportScroll(rs);
		} catch (final SQLException e) {
			_log.log(Level.SEVERE,
					"error while creating william_teleport_scroll table", e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
}
